#!/bin/bash

# MySQL root 密码重置脚本
# 需要 root 权限执行

set -e

MYSQL_DIR="/usr/local/mysql"
MYSQL_DATA_DIR="/var/lib/mysql"
MYSQL_USER="mysql"
NEW_PASSWORD="root"

echo "重置 MySQL root 密码..."

# 检查是否以 root 权限运行
if [ "$EUID" -ne 0 ]; then 
    echo "错误: 请使用 sudo 运行此脚本"
    echo "使用方法: sudo bash reset_mysql_password.sh"
    exit 1
fi

# 方法1: 尝试使用 --skip-grant-tables 重置密码
echo "停止 MySQL 服务..."
systemctl stop mysql 2>/dev/null || pkill mysqld || true
sleep 2

echo "以跳过权限表模式启动 MySQL..."
cd "$MYSQL_DIR"
bin/mysqld_safe --skip-grant-tables --skip-networking --user=$MYSQL_USER --datadir="$MYSQL_DATA_DIR" &
MYSQL_PID=$!
echo "等待 MySQL 启动..."
sleep 5

echo "重置 root 密码..."
bin/mysql -u root <<EOF
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY '$NEW_PASSWORD';
FLUSH PRIVILEGES;
EOF

echo "停止临时 MySQL 进程..."
kill $MYSQL_PID 2>/dev/null || true
sleep 2

echo "启动 MySQL 服务..."
systemctl start mysql
sleep 3

echo "验证密码..."
if bin/mysql -u root -p"$NEW_PASSWORD" -e "SELECT 1;" >/dev/null 2>&1; then
    echo ""
    echo "=========================================="
    echo "密码重置成功！"
    echo "=========================================="
    echo "用户名: root"
    echo "密码: $NEW_PASSWORD"
    echo ""
    echo "现在可以使用以下命令连接："
    echo "  mysql -u root -p$NEW_PASSWORD"
    echo "  或"
    echo "  mysql -u root -p"
    echo "  (然后输入密码: $NEW_PASSWORD)"
    echo "=========================================="
else
    echo "警告: 密码验证失败，可能需要手动检查"
fi

